#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
DELETE FROM `wp_terms` WHERE `term_id` >5;
DELETE FROM `wp_term_taxonomy` WHERE `term_taxonomy_id` >5;
DELETE FROM `wp_term_relationships` WHERE `object_id` >5;
DELETE FROM `wp_posts` WHERE `ID` >10;

ALTER TABLE `wp_terms` auto_increment=10 ;
ALTER TABLE `wp_term_taxonomy` auto_increment=10 ;
ALTER TABLE `wp_term_relationships` auto_increment=10 ;
ALTER TABLE `wp_posts` auto_increment=20 ;

'''
from model import database as db, WpTermRelationships, WpTermTaxonomy, WpTerms, WpPosts
from slugify import slugify
from peewee import *
import uuid

db.connect()


class WordPressPost():
    '''
    '''
    title = ''  # 文章标题
    content = ''  # 文章正文
    post_status = ''  # 文章状态，不写默认是草稿，private表示私密的，draft表示草稿，publish表示发布
    thumbnail = 0  # 缩略图的id
    terms_names = []  # 分类名字列表

    def NewPost(self):
        term_lst = []
        try:
            for terms in self.terms_names:
                term_lst.append(WordPressTerm(terms).get_or_create_Term())
        except Exception, ex:
            print ex

        if self.post_status != 'publish'and self.post_status != 'private' and self.post_status != 'draft':
            self.post_status = 'publish'

        with db.atomic() as transaction:  # 使用事务存
            try:

                wpPosts = WpPosts(
                    post_title=self.title,
                    post_content=self.content,
                    post_status=self.post_status,
                    guid=uuid.uuid4(),
                    post_name=slugify(self.title),
                )
                wpPosts.save()

                for term in term_lst:
                    print 'object_id=%s, term_taxonomy_id=%s' % (wpPosts.id, term.term_id)
                    wpTermTaxonomy = WpTermTaxonomy.get(
                        WpTermTaxonomy.term == term)
                    wpTermRelationships = WpTermRelationships(object=wpPosts,
                                                              term_taxonomy=wpTermTaxonomy)
                    wpTermRelationships.save()
                return wpPosts

            except Exception, ex:
                print ex
                db.rollback()
                return None

    def count(self,ALL=True):
        pass
        


class WordPressTerm(self):
    taxonomy = ''  # 决定是tag还是category post_tag or category
    name = ''  # 名字
    slug = ''  # 缩写
    description = ''  # 描述
    parent = 0  # 所属父分类方法ID
    count = 0  # 文章数统计

    def __init__(self, name, slug='', taxonomy='', description='', parent=0, count=0):
        '''
        '''
        self.name = name

        if len(self.slug) < 1:  # 如果slug为空，自动生产slug
            self.slug = slugify(self.name)
        else:
            self.slug = slug

        if taxonomy != 'category' and taxonomy != 'post_tag':
            self.taxonomy = 'category'
        else:
            self.taxonomy = taxonomy

        self.description = description
        self.parent = parent
        self.count = count

    def NewTerm(self):

        if len(self.name) < 1:  # 如果name为空，返回None
            return None

        with db.atomic() as transaction:  # 使用事务
            try:
                
                wpTerms = WpTerms(name=self.name, slug=self.slug)
                wpTerms.save()
                
                wpTermTaxonomy = WpTermTaxonomy(
                    term=wpTerms,
                    taxonomy=self.taxonomy,
                    description=self.description,
                    parent=self.parent,
                    count=self.count)

                wpTermTaxonomy.save()

                return wpTerms

            except Exception, ex:
                print 'NewTerm : %s' % ex
                db.rollback()
                return None

    def get_or_create_Term(self):
        try:
            print 'ddddddddd%s'%self.slug
            wpTerms = WpTerms.get(WpTerms.name == self.name,
                                  WpTerms.slug == self.slug)
            return wpTerms

        except Exception, ex:
            #print 'get_or_create_Term : %s'%ex
            return self.NewTerm()


if __name__ == '__main__':

    far_Term = WordPressTerm('父测试分类').get_or_create_Term()
    print far_Term
    sub_Term = WordPressTerm('子测试分类', parent=far_Term.term_id).get_or_create_Term()
    print sub_Term

    wpPost = WordPressPost()
    wpPost.title = "测试标题2"
    wpPost.content = '测试内容2'
    wpPost.terms_names = ['子测试分类','测试内容']
    print wpPost.NewPost()
